package com.cetccst.securitysuite.mqtt;

import android.content.Context;

import com.cetccst.securitysuite.log.SSLogger;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import cn.com.cetccst.mqtt.ISSMqttClient;
import cn.com.cetccst.mqtt.MqttManager;

public class SSMqtt {

    public static final String TOPIC_TEST = "topic_test";
    private static SSMqtt instance;
    public ISSMqttClient mqttClient;
    private final Map<String, Set<Callback>> topicCallbacks = new HashMap<>();

    public interface Callback {
        void onMessageArrived(String message);
    }

    private SSMqtt(Context context, String url) {
        if (mqttClient == null) {
            mqttClient = new MqttManager.Builder(context, url, state -> SSLogger.logger.info(state.toString())).build();
            MqttManager.setLogger(SSLogger.logger);
            mqttClient.subscribeTopic(TOPIC_TEST, message -> {
                Set<Callback> callbacks = topicCallbacks.get(TOPIC_TEST);
                if (callbacks != null) {
                    for (Callback callback : callbacks) {
                        callback.onMessageArrived(message);
                    }
                }
            });
        }
    }

    public static void initialize(Context context, String url) {
        if (instance == null) {
            instance = new SSMqtt(context, url);
        }
    }

    public static SSMqtt getInstance() {
        return instance;
    }

    public void connect() {
        mqttClient.connect();
    }

    public void subscribe(String topic, Callback callback) {
        Set<Callback> callbacks = topicCallbacks.get(topic);
        if (callbacks == null) {
            callbacks = new HashSet<>();
            topicCallbacks.put(topic, callbacks);
        }
        callbacks.add(callback);
    }

    public void unsubscribe(String topic, Callback callback) {
        Set<Callback> callbacks = topicCallbacks.get(topic);
        if (callbacks != null) {
            callbacks.remove(callback);
        }
    }
}
